<!-- 视频上传组件 -->
<template>
  <section class="box">
    <el-upload
      class="upload"
      :accept="accept"
      drag
      :show-file-list="false"
      :before-upload="handleBeforeUpload"
      :http-request="handleHttpRequest"
    >
      <template #default>
        <div>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div>拖拽文件或 <em>点击上传</em></div>
        </div>
      </template>
      <template #tip>
        <div>请上传小于{{ byteSize }}的视频</div>
        <el-progress :percentage="progressNum" />
      </template>
    </el-upload>
    <figure class="video-box" v-if="path">
      <video
      :src="path"
      controls
      class="video"/>
    </figure>
  </section>
</template>
  
  <script setup lang="ts">
import { defineProps, defineEmits, computed,ref } from "vue";
import type { UploadRawFile,UploadRequestOptions } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { getByteSize } from "@/utils/tool";
import getUpload from "@/utils/qiniu";
import request from "@/utils/request";

const props = defineProps({
  // 七牛云的中文件的key
  modelValue: {
    type: String,
    required: true,
  },
  // 允许上传的mimeType（默认为所有视频类型）
  accept: {
    type: String,
    default: "video/*",
    required: false,
  },
  // 允许上传文件的最大字节数
  contentLength: {
    type: Number,
    // 默认400M
    default: 1024 * 1024 * 400,
    required: false,
  },
});

// 定义自定义事件触发器
const emits = defineEmits(["update:modelValue"]);

const path = ref<string>("");

const { asyncRequest, progressNum } = getUpload(true);

const byteSize = computed(() => getByteSize(props.contentLength));

/**
 * 上传预校验，如果返回false，那么阻止文件上传
 * @param rawFile
 */
function handleBeforeUpload(rawFile: UploadRawFile) {
  // 只能小于2mb的文件
  if (rawFile.size > props.contentLength) {
    alert({ type: "error", message: `请上传小于${byteSize.value}的文件` });
    return false;
  }
  // 只能上传视频：
  const contentType = props.accept.replace("*", "");
  if (!rawFile.type.startsWith(contentType)) {
    alert({ type: "error", message: "请上传合法的视频格式" });
    return false;
  }
}

/**
 * 上传文件
 * @param rawFile
 */
const handleHttpRequest = (rawFile: UploadRequestOptions) => {
  asyncRequest(rawFile).then((res) => {
    emits("update:modelValue", res.key);
    // 使用key通过接口获取文件的url
    request({url:"/qiniu/getSourceURL/" + res.key,method:"get"}).then((res) => {
      path.value = res.data.data;
    });
    // emits("update:modelValue", res.file_path);
  });
}
</script>
  
<style scoped lang="scss">
.box {
  width: 100%;
}

.el-tabs {
  width: 100%;
}

.video-box {
  .video {
    max-width: 100%;
  }
}
</style>